<?php

namespace App\Http\Controllers\Item;

use App\Models\Item;
use App\Models\ItemCatlog;
use App\Models\ItemContent;
use App\Models\ItemImage;
use App\Models\ItemProps;
use App\Models\Shop;
use Jenssegers\Agent\Facades\Agent;

class DetailController extends BaseController
{
    public function index($itemid) {

        if (Agent::isMobile()) {
            return redirect(mobile_item_url($itemid));
        }

        $iteminfo = Item::find($itemid);
        if (!$iteminfo) {
            return $this->showError(trans(trans('mall.item_not_exists')));
        }else {
            $iteminfo->incrementViews();
            if ($iteminfo->on_sale) {
                $this->assign(['iteminfo'=>$iteminfo, 'itemid'=>$itemid]);

                $content = ItemContent::where('itemid', $itemid)->first();
                $this->assign(['content'=>$content]);

                $images = ItemImage::where('itemid', $itemid)->orderBy('displayorder')->get();
                if (!$images) {
                    $images = [
                        [
                            'thumb'=>$iteminfo['thumb'],
                            'image'=>$iteminfo['image']
                        ]
                    ];
                }
                $this->assign(['images'=>$images]);

                $shop = Shop::where('shop_id', $iteminfo['shop_id'])->first();
                $this->assign(['shop'=>$shop]);

                $catlog = ItemCatlog::where('catid', $iteminfo['catid'])->first();
                $this->assign(['catlog'=>$catlog]);

                $properties = ItemProps::where('itemid', $itemid)->orderBy('prop_id')->get();
                $this->assign(['properties'=>$properties]);

                //掌柜热卖
                $hotSaleList = Item::where(['shop_id'=>$iteminfo['shop_id'],'on_sale'=>1])->orderByDesc('sold')->limit(5)->get();
                $this->assign(['hotSaleList'=>$hotSaleList]);

                return $this->view('item.detail');
            } else {
                return $this->showError(trans('mall.commodity has already gone off shelves'));
            }
        }
    }
}
